package com.fancy.learncenter.activity;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.activity.base.BaseActivity;
import com.fancy.learncenter.adapter.PingLunAdapter;
import com.fancy.learncenter.adapter.base.CommonRecycleViewAdapter;
import com.fancy.learncenter.adapter.base.CustomViewHold;
import com.fancy.learncenter.bean.BaseDataBean;
import com.fancy.learncenter.bean.CommentsDataBean;
import com.fancy.learncenter.bean.GoodsDetailDataBean;
import com.fancy.learncenter.bean.RongYunDataBean;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.net.IdeaObserver;
import com.fancy.learncenter.utils.SPUtils;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.fancy.learncenter.utils.WXShareUtil;
import com.fancy.learncenter.view.PopupWindowSendDiscuss;
import com.superservice.lya.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;

public class GoodsDetailActivity extends BaseActivity {


    ArrayList<String> mData;

    SimpleDraweeView user_icon;
    TextView name;
    TextView time;
    TextView tz_title;
    TextView praise_num;
    TextView praise_bt;
    TextView content;
    TextView old_price;
    TextView price;
    TextView answer_num;

    RecyclerView pic_recycleView;

    @Bind(R.id.recycleView)
    RecyclerView recycleView;

    String goodsId = "";
    @Bind(R.id.shoucang_icon)
    ImageView shoucangIcon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail, getResources().getColor(R.color.toolbar_color));
        ButterKnife.bind(this);

        initToolbar("闲置物品");
//        goodsId = (GoodsDataBean) getIntent().getSerializableExtra("GoodsD／ataBean");
        goodsId = getIntent().getStringExtra("GoodsDataBean");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        getWidth();
        getData();

        initView();

        wdCommenLists();


        popupWindowSendDiscuss = new PopupWindowSendDiscuss(this, recycleView);

        popupWindowSendDiscuss.setSendDisCallBack(new PopupWindowSendDiscuss.SendDisCallBack() {
            @Override
            public void sendDiscuss() {

                if (!TextUtils.isEmpty(SPUtils.getToken())) {
                    if (Utils.isFastClick()) {
                        if (discussTz) {
                            wDComment();
                        } else {
                            goodsCommentReply();
                        }
                    }

                } else {
                    Intent intent = new Intent(GoodsDetailActivity.this, LoginActivity.class);
                    startActivity(intent);
                }


            }
        });
    }

    List<CommentsDataBean> listDataBean = new ArrayList<>();

    PopupWindowSendDiscuss popupWindowSendDiscuss;
    ImageView wx_icon;
    ImageView wx_friend;
    int width = 0;

    private void getWidth() {
        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density = dm.density;
        width = dm.widthPixels;
    }

    private void initView() {
        View headerView = LayoutInflater.from(this).inflate(R.layout.activity_goodsdetail_header, null);
        headerView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        user_icon = (SimpleDraweeView) headerView.findViewById(R.id.user_icon);
        user_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.goToPersonInfo(GoodsDetailActivity.this, user_id);
            }
        });

        wx_icon = headerView.findViewById(R.id.wx_icon);
        wx_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WXShareUtil.getInstance(GoodsDetailActivity.this).shareWebPage(shareUrlPic, shareTitle, shareContent, shareLinkUrl, false);
            }
        });

        wx_friend = headerView.findViewById(R.id.wx_friend);
        wx_friend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WXShareUtil.getInstance(GoodsDetailActivity.this).shareWebPage(shareUrlPic, shareTitle, shareContent, shareLinkUrl, true);
            }
        });

        name = (TextView) headerView.findViewById(R.id.name);

        time = (TextView) headerView.findViewById(R.id.time);


        old_price = (TextView) headerView.findViewById(R.id.old_price);
        //中划线.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG); //中划线

        price = (TextView) headerView.findViewById(R.id.price);


        praise_num = (TextView) headerView.findViewById(R.id.praise_num);


        answer_num = (TextView) headerView.findViewById(R.id.answer_num);

//        praise_bt = (TextView) headerView.findViewById(R.id.praise_bt);
//        praise_bt.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                ToastUtil.show("收藏成功");
//            }
//        });


        content = (TextView) headerView.findViewById(R.id.content);


        pic_recycleView = (RecyclerView) headerView.findViewById(R.id.pic_recycleView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        pic_recycleView.setLayoutManager(linearLayoutManager);
        picAdapter = new CommonRecycleViewAdapter<String>(this, R.layout.good_detail_pic_item, new ArrayList<String>()) {
            @Override
            public void bindView(CustomViewHold customViewHold, String item, final int position) {
                SimpleDraweeView simpleDraweeView = customViewHold.getView(R.id.simpleDraweeView);
                simpleDraweeView.setImageURI(item);
                simpleDraweeView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(GoodsDetailActivity.this, GalleryPicDetailActivity.class);
                        intent.putStringArrayListExtra(GalleryPicDetailActivity.PIC_KEY, picAdapter.itemDatas);
                        intent.putExtra(GalleryPicDetailActivity.PIC_POSITION_KEY, position);

                        startActivity(intent);

                    }
                });

//                Utils.setControllerListener(simpleDraweeView, item, width);
            }
        };
        pic_recycleView.setAdapter(picAdapter);

        initRecycle(headerView);

    }

    ArrayList<String> picData = new ArrayList<>();

    CommonRecycleViewAdapter<String> picAdapter;
    PingLunAdapter adapter;

    private void initRecycle(View view) {
        ArrayList mData = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(linearLayoutManager);
        adapter = new PingLunAdapter(this, mData);
        recycleView.setAdapter(adapter);
        adapter.setHeaderView(view, recycleView);


        adapter.setOnClickCallBack(new PingLunAdapter.OnClickCallBack() {
            @Override
            public void OnClick(int position) {
                discussTz = false;

                commentId = listDataBean.get(position).getId();

                popupWindowSendDiscuss.showPop();
            }
        });
    }


    private boolean discussTz = true;

    private String commentId;
    String shareUrlPic = "";
    String shareTitle = "";
    String shareContent = "";
    String shareLinkUrl = "";


    private void getData() {
        Map map = new HashMap();
        map.put("goodsId", goodsId);

        HttpMehtod.getInstance().goodsDetail(map, new IdeaObserver<BaseDataBean<GoodsDetailDataBean>>(this, true) {

            @Override
            public void onSuccess(BaseDataBean<GoodsDetailDataBean> goodsDetailDataBeanBaseDataBean) {

                shareUrlPic = goodsDetailDataBeanBaseDataBean.getData().getShare_img();
                shareContent = goodsDetailDataBeanBaseDataBean.getData().getShare_content();
                shareLinkUrl = goodsDetailDataBeanBaseDataBean.getData().getShare_link();
                shareTitle = goodsDetailDataBeanBaseDataBean.getData().getShare_title();

                time.setText(goodsDetailDataBeanBaseDataBean.getData().getAdd_time() + "发布");

                name.setText(goodsDetailDataBeanBaseDataBean.getData().getNick_name());
                user_icon.setImageURI(goodsDetailDataBeanBaseDataBean.getData().getUser_img());

                old_price.setText("¥" + goodsDetailDataBeanBaseDataBean.getData().getOld_price() + "");
                old_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                price.setText("¥" + goodsDetailDataBeanBaseDataBean.getData().getPrice());
                praise_num.setText(goodsDetailDataBeanBaseDataBean.getData().getComment_num());
                content.setText(goodsDetailDataBeanBaseDataBean.getData().getDescription());


                if (goodsDetailDataBeanBaseDataBean.getData().getImg_src() != null) {
                    picAdapter.notifyDataSetChanged((ArrayList) goodsDetailDataBeanBaseDataBean.getData().getImg_src());
                }


                if (goodsDetailDataBeanBaseDataBean.getData().getIs_collect() == 0) {
                    mCollect = false;
                    shoucangIcon.setImageResource(R.mipmap.ic_shoucang_gray);
                } else {
                    mCollect = true;
                    shoucangIcon.setImageResource(R.mipmap.ic_shoucangdown);
                }
                user_id = goodsDetailDataBeanBaseDataBean.getData().getUser_id();

            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }

    private void wDComment() {
        Map map = new HashMap();
        map.put("goodsId", goodsId);
        map.put("content", popupWindowSendDiscuss.getDiscuss());

        HttpMehtod.getInstance().goodsComment(map, new IdeaObserver<BaseDataBean>(this, true) {
            @Override
            public void onSuccess(BaseDataBean listBaseDataBean) {
                wdCommenLists();

                ToastUtil.show("评论成功");
                popupWindowSendDiscuss.dismiss();
            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }

    private void goodsCommentReply() {
        Map map = new HashMap();
        map.put("goodsId", goodsId);
        map.put("content", popupWindowSendDiscuss.getDiscuss());
        map.put("commentId", commentId);

        HttpMehtod.getInstance().goodsCommentReply(map, new IdeaObserver(this, true) {
            @Override
            public void onSuccess(BaseDataBean listBaseDataBean) {

                ToastUtil.show("评论成功");
                popupWindowSendDiscuss.dismiss();
                popupWindowSendDiscuss.getDiscuss();
                wdCommenLists();
            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }

    private void wdCommenLists() {
        Map map = new HashMap();
        map.put("goodsId", goodsId + "");

        HttpMehtod.getInstance().goodsCommenLists(map, new IdeaObserver<BaseDataBean<List<CommentsDataBean>>>(this, true) {

            @Override
            public void onSuccess(BaseDataBean<List<CommentsDataBean>> listBaseDataBean) {

                if (listBaseDataBean.getData() != null) {

                    listDataBean = listBaseDataBean.getData();
                    adapter.notifyDataSetChanged((ArrayList<CommentsDataBean>) listBaseDataBean.getData());

                    answer_num.setText("回帖列表（" + listBaseDataBean.getData().size() + "）");
                }

            }

            @Override
            public void onFail(int errorCode) {

            }
        });

    }


    boolean mCollect = false;

    private void collect() {
        Map map = new HashMap();
        map.put("relationId", goodsId + "");
        map.put("type", "2");

        HttpMehtod.getInstance().collect(map, new IdeaObserver<BaseDataBean>(this, true) {


            @Override
            public void onSuccess(BaseDataBean baseDataBean) {
                mCollect = true;
                shoucangIcon.setImageResource(R.mipmap.ic_shoucangdown);
            }

            @Override
            public void onFail(int errorCode) {

            }
        });

    }

    private void cancelCollect() {
        Map map = new HashMap();
        map.put("relationId", goodsId + "");
        map.put("type", "2");

        HttpMehtod.getInstance().cancelCollect(map, new IdeaObserver<BaseDataBean>(this, true) {

            @Override
            public void onSuccess(BaseDataBean baseDataBean) {
                mCollect = false;
                shoucangIcon.setImageResource(R.mipmap.ic_shoucang_gray);
            }

            @Override
            public void onFail(int errorCode) {

            }
        });

    }


    String user_id = "";

    @OnClick({R.id.shoucang, R.id.sub_discuss, R.id.msg})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.shoucang:
                if (!TextUtils.isEmpty(SPUtils.getToken())) {

                    if (mCollect) {
                        cancelCollect();
                    } else {
                        collect();
                    }
                } else {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                }

                break;
            case R.id.sub_discuss:
                if (!TextUtils.isEmpty(SPUtils.getToken())) {
                    discussTz = true;
                    popupWindowSendDiscuss.showPop();
                } else {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                }

                break;
            case R.id.msg:

                if (!TextUtils.isEmpty(SPUtils.getToken())) {

                    if (TextUtils.isEmpty(name.getText().toString())) {
                        RongIM.getInstance().startPrivateChat(this, user_id, "匿名");
                    } else {
                        RongIM.getInstance().startPrivateChat(this, user_id, name.getText().toString());
                    }

                } else {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                }


                break;
        }
    }
}
